package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.FelEngine;
import com.greenpineyu.fel.context.ContextChain;
import com.greenpineyu.fel.context.FelContext;
import com.greenpineyu.fel.context.MapContext;
import com.tfswx.ruleengine.compute.bean.DataObject;
import com.tfswx.ruleengine.compute.bean.GzBdsDTO;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ricky
 * @date 2021/6/15
 */
public class Someone extends BaseFn {
    @Override
    public Object call(Object[] arguments, FelContext context) {
        String bmc = String.valueOf(arguments[0]);
        String bds = String.valueOf(arguments[1]);

        GzBdsDTO gzObj = (GzBdsDTO) context.get("currGz");
        DataObject data = (DataObject) context.get("$curr");

        if (data == null) {
            List<DataObject> dataList = (List<DataObject>) context.get("dataList");

            data = dataList.stream().filter(item -> item.getStbm().equals(gzObj.getBmc())).findFirst().orElse(null);
        }
        if (data == null) {
            throw new AppException("请确认表名称是否选择正确");
        }
        List<DataObject> collect = data.getCbsj().stream().filter(item -> item.getStbm().equals(bmc)).collect(Collectors.toList());

        FelEngine fel = (FelEngine) context.get("fel");
        FelContext ctx = new ContextChain(context, new MapContext());

        for (DataObject dataObject : collect) {
            List<DataObject.ZdItemDTO> zdsj = dataObject.getZdsj();
            Map<String, String> map = new HashMap<>();
            for (DataObject.ZdItemDTO zdItemDTO : zdsj) {
                map.put(zdItemDTO.getZdmc(), zdItemDTO.getBgqzdbmz());
            }
            ctx.set(bmc, map);
            ctx.set("$data", dataObject);
            Boolean eval = (Boolean) fel.eval(bds, ctx);
            if (Boolean.TRUE.equals(eval)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public String getZwmc() {
        return "存在";
    }


    @Override
    public List<Param> getParams() {
        ArrayList<Param> params = new ArrayList<>();
        params.add(new Param("bmc"));
        params.add(new Param("bds"));
        return params;
    }

    @Override
    public String getName() {
        return "someone";
    }
}
